package testJdk.nio.testChannel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class TestServerSocketChannel {

    public static void main(String[] args) throws Exception {
        // 监听端口
        int port = 8888;
        // 设置buffer，里面是响应内容
        ByteBuffer byteBuffer = ByteBuffer.wrap("hello cyd".getBytes());
        // 获得serverChannel实例
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 用socket绑定监听端口
        ssc.socket().bind(new InetSocketAddress(port));
        // 设置为非阻塞模式
        ssc.configureBlocking(false);
        // 循环监听
        while (true){
            System.out.println("waiting for connection...");
            SocketChannel sc = ssc.accept();
            if (sc==null){ // 如果没有连接进来，sc就是null
                System.out.println("null");
                Thread.sleep(2000);
            }else { // 如果有连接进来，就打印连接发起的端口号
                System.out.println("connection from "+sc.socket().getRemoteSocketAddress());
                // 将响应写入进入socket，并返回给访问者
                byteBuffer.rewind();
                sc.write(byteBuffer);
                sc.close();
            }
        }

    }
}
